<?php
/**
 *
 * @author Strawberry🍓
 * @date 2021-05-31 2:34 下午
 *
 */

namespace app\api\controller;


use app\api\service\AliService;
use app\api\service\GPService;
use app\api\service\HaiDing;
use app\api\service\JwtService;
use app\api\service\MarketingService;
use app\api\service\MemberService;
use app\api\service\message;
use app\api\service\Request;
use app\common\energyApi\JieShun;
use app\common\model\tang\BalanceAudit;
use app\common\model\tang\BalanceLog;
use app\common\model\tang\Close;
use app\common\model\tang\Config;
use app\common\model\tang\Config as CompanyConfig;
use app\common\model\tang\CostAudit;
use app\common\model\tang\CostLog;
use app\common\model\tang\CostSectionPay;
use app\common\model\tang\CostType;
use app\common\model\tang\Invoice;
use app\common\model\tang\MerchantEmployees;
use app\common\model\tang\MerchantExtra;
use app\common\model\tang\MerchantInvoice;
use app\common\model\tang\MerchantLog;
use app\common\model\tang\MerchantMonthMoney;
use app\common\model\tang\MerchantReadingLog;
use app\common\model\tang\MerchantShift;
use app\common\model\tang\MonthElectricityDegree;
use app\common\model\tang\MonthElectricityRecord;
use app\common\model\tang\MonthSoleElectricityLog;
use app\common\model\tang\MonthWaterLog;
use app\common\model\tang\PayInfo;
use app\common\model\tang\ReleaseUser;
use app\common\model\tang\SubjectList;
use app\common\model\tang\WatchMaintain;
use think\App;
use app\common\model\tang\Task;
use app\common\model\tang\Merchant as MerchantModel;
use app\common\model\tang\MerchantMobile as MerchantMobileModel;
use app\common\model\tang\Cost;
use think\Exception;
use think\facade\Db;
use think\facade\Log;

class Merchant extends Base
{
    /**
     *手机号授权登录
     */
    public function PhoneLogin()
    {
        $code = $this->request->param('code');
        $iv = $this->request->param('iv');
        $encryptedData = $this->request->param('encryptedData');
        if (empty($code) || empty($iv) || empty($encryptedData)) {
            return SendError("参数错误");
        }
        $getUserInfo = $this->app->openPlatform->auth->session($code); //返回openid 和 sessionkey
        if (!isset($getUserInfo['session_key']) || empty($getUserInfo['session_key'])) {
            return SendError("code不不正确");
        }
        $decryptedData = $this->app->openPlatform->encryptor->decryptData($getUserInfo['session_key'], $iv, $encryptedData);
        $mobile = $decryptedData['phoneNumber'];
        $info = MerchantModel::where(['mobile' => $mobile])->where('status', 1)->find();
        //员工登录
        $employess = MerchantEmployees::where(['mobile' => $mobile])->order('id desc')->where('status', 1)->field('id,merchant_id')->find();
        if (empty($info) && empty($employess)) {
            return SendError("你不是商户无法登陆");
        }
        if (!empty($info)) {
            if ($info['status'] == -1) {
                return SendError("账户已冻结，请联系管理员");
            }
            MerchantModel::update(['openid' => $getUserInfo['openid'], 'unionid' => $getUserInfo['unionid']], ['id' => $info['id']]);
        } else {

            if (!empty($employess)) {
                if ($employess['is_type'] == 2) { //员工账号无法登陆
                    return SendError("员工账号无法登陆");
                }
                if ($employess['status'] == -1) {
                    return SendError("账户已冻结，请联系门店负责人");
                }
                $info['id'] = $employess['merchant_id'];
                MerchantEmployees::update(['openid' => $getUserInfo['openid'], 'unionid' => $getUserInfo['unionid']], ['id' => $employess['id']]);
            }
        }

        $jwtAuth = JwtService::getInstance();
        $token = $jwtAuth->setOpenid($getUserInfo['openid'])
            ->setUid($info['id'])
            ->setMobile($mobile)
            ->encode()
            ->getToken();
        $data['staff'] = [];
        if (isset($staff)) {
            $data['staff'] = $staff;
        }
        $data['token'] = $token;
        return SendSuccess("登录成功", $data);

    }

    /**
     *账号密码登录
     */
    public function login()
    {
        $openid = $this->request->param('openid');
        $account = $this->request->param('account');
        $password = $this->request->param('password');
        if (empty($account) || empty($password) || empty($openid)) {
            return SendError('账号密码不能为空');
        }
        $info = MerchantModel::where(['mobile' => $account])->field('id,password,status')->where('status', 1)->find();
        $staff = MerchantEmployees::where(['mobile' => $account])->order('id desc')->where('status', 1)->find();
        if (empty($info) && empty($staff)) {
            return SendError("商户不存在");
        }
        if (!empty($info)) {
            //TODO 检测密码是否正确
            if (md5($password) !== $info['password']) {
                return SendError("密码错误");
            }
            if ($info['status'] == -1) {
                return SendError("账户已冻结，请联系管理员");
            }
            MerchantModel::update(['openid' => $openid], ['id' => $info['id']]);
        } else {
            if (!empty($staff)) {
                if (md5($password) !== $staff['password']) {
                    return SendError("密码错误");
                }
                if ($staff['is_type'] == 2) { //员工账号无法登陆
                    return SendError("员工账号无法登陆");
                }
                if ($staff['status'] == -1) {
                    return SendError("账户已冻结，请联系门店负责人");
                }
                $info['id'] = $staff['merchant_id'];
                MerchantEmployees::update(['openid' => $openid], ['id' => $staff['id']]);
            }
        }
        $merchantLog = (new MerchantLog())->where('openid', $openid)->find();
        if (empty($merchantLog)) {
            $log['openid'] = $openid;
            $log['username'] = $account;
            $log['password'] = $password;
            (new MerchantLog())->save($log);
        } else {
            $log['username'] = $account;
            $log['password'] = $password;
            (new MerchantLog())->update($log, ['id' => $merchantLog['id']]);
        }
        $jwtAuth = JwtService::getInstance();
        $token = $jwtAuth->setOpenid($openid)
            ->setUid($info['id'])
            ->setMobile($account)
            ->encode()
            ->getToken();
        $data['staff'] = [];
        if (isset($staff)) {
            $data['staff'] = $staff;
        }
        $data['token'] = $token;
        return SendSuccess("登录成功", $data);
    }

    /**
     * 商家添加员工调整
     */
    public function addEmployeesNew()
    {
        $employees = $this->request->param();
        if (empty($employees['merchant_id'])) {
            return SendError('请选择商户');
        }
//        if (empty($employees['member_role'])) {
//            return SendError('请选择会员系统权限');
//        }
//        if (empty($employees['marketing_role'])) {
//            return SendError('请选择支付营销系统权限');
//        }
        $merchant_id = $employees['merchant_id'];
        Db::startTrans();
        try {
            $Merchant = MerchantModel::where(['id' => $merchant_id])->field('id,merchant_sn,status,mobile,username,company,name')->find();
            if (empty($Merchant)) {
                return SendError('商户不存在');
            }
            $isFirst = (new MerchantEmployees)->where(['mobile' => $employees['mobile']])->where('status', '<>', '-1')->find();
            if ($isFirst) {
                return SendError('该员工已存在');
            }
            $mobile = $this->mobile;
            if ($Merchant['mobile'] == $mobile) { //说明是总管理创建
                $employees['is_type'] = 1;
            } else {
                $employees['is_type'] = 2; //说明是店长创建
            }
            /**
             * 检测照片是否合法
             */
            $jieshun = new JieShun();
            $image_data = file_get_contents($employees['portrait']);
            $pic = ['picBase64' => base64_encode($image_data)];
            $res = $jieshun->facecheck($pic);
            if (isset($res['code']) && $res['code'] != 0) {
                return SendError($res);
            }
            $employees['create_time'] = time();
            $employees['password'] = md5(123456);
            $employees['merchant_id'] = $merchant_id;
            (new MerchantEmployees)->save($employees);
            Db::commit();
            return SendSuccess('添加成功');
        } catch (\Exception $exception) {
            // 回滚事务
            Db::rollback();
            return SendError($exception->getMessage());
        }

    }

    /**
     * 获取商户店铺
     */
    public function getBrandInfo()
    {
        $info = (new MerchantModel())->where('mobile', $this->mobile)->where('status', 1)->select();
        return SendSuccess('success', $info);
    }

    /**
     * 余额变更申请
     */
    public function balanceApply()
    {
        $param = $this->request->param();
        if (empty($param['new_merchant_id'])) {
            return SendError('请选择老商户');
        }
        if ($this->merchant_id == $param['new_merchant_id']) {
            return SendError('转移和待转移不能相同');
        }
        $new = MerchantModel::where(['id' => $param['new_merchant_id']])->value('merchant_sn');
        $old = MerchantModel::where(['id' => $this->merchant_id])->value('merchant_sn');
        if ($new != $old) {
            return SendError('请选择同主体合同进行转移');
        }
        $model = new MerchantShift();
        $balance = MerchantModel::where(['id' => $param['new_merchant_id']])->value('balance');
        $isFirst = $model->where(['new_merchant_id' => $this->merchant_id, 'status' => 0])->find();
        if ($isFirst) {
            return SendError('正在审核中');
        }
        try {
            $model->merchant_id = $param['new_merchant_id'];
            $model->new_merchant_id = $this->merchant_id;
            $model->balance = $balance;
            $model->create_time = time();
            $model->save();
            return SendSuccess('申请成功', '');
        } catch (\Exception $e) {
            return SendError($e->getMessage());
        }

    }

    public function getUserInfo()
    {
        $result = MerchantModel::where(['id' => $this->merchant_id])->find();
        $da = MerchantModel::where(['mobile' => $this->getMobile()])->find();
        $staff = MerchantEmployees::where(['mobile' => $this->getMobile()])->order('create_time desc')->find();
        if (empty($result) && empty($staff)) {
            return SendError("该用户不存在");
        }
        $chargeMoney = BalanceLog::where(['merchant_id' => $this->merchant_id, 'status' => 1, 'is_top_up' => 1])->whereTime('charge_time', 'month')->sum('amount');
        $costMoney = (new Cost())->where(['merchant_id' => $this->merchant_id, 'pay_status' => 0])->sum('amount');
        $result['username'] = $result['name'].'-'.$result['username'];
        $result['chargeMoney'] = bcdiv($chargeMoney, 100, 2);;
        $result['oweMoney'] = bcdiv($costMoney, 100, 2);
        $result['balance'] = bcdiv($result['balance'], 100, 2);
        $result['frozen_balance'] = bcdiv($result['frozen_balance'], 100, 2);
        $result['start_balance'] = bcadd($result['balance'], $result['frozen_balance'], 2);
        if ($result['ytCode'] == '03') {
            $result['isRepast'] = 1;
        } else {
            $result['isRepast'] = 0;
        }
        if ($result) {
            $result['isStaff'] = 0;
        }
        if ($staff) {
            $result['username'] = $result['name'].'-'.$staff['name'];
            $result['mobile'] = $staff['mobile'];
            if ($staff['is_type'] == 1) {
                $result['isStaff'] = 1; //店长
            } else {
                $result['isStaff'] = 2; //员工
            }

        }
        if (!empty($staff) && !empty($da)) {
            $result['isStaff'] = 0;
        }
        return SendSuccess("success", $result);
    }

    /**
     * 查看商户余额
     */
    public function BalanceInfo()
    {
        $merchant_id = $this->merchant_id;
        $result = MerchantModel::where(['id' => $merchant_id])->find();
        $data['startBalance'] = $result['start_balance']; //期初余额
        $data['balance'] = $result['balance'];//现在余额
        $data['electrity'] = Cost::where(['merchant_id' => $merchant_id, 'type' => 4, 'pay_status' => 1])->sum('amount');//电费
        $data['water'] = Cost::where(['merchant_id' => $merchant_id, 'type' => 5, 'pay_status' => 1])->sum('amount');//水费
        $data['charge'] = BalanceLog::where(['merchant_id' => $merchant_id, 'status' => 1, 'is_top_up' => 1])->sum('amount');//充值
        if ($data['startBalance'] > 0) $data['startBalance'] = $data['startBalance'] / 100;
        if ($data['balance'] > 0) $data['balance'] = $data['balance'] / 100;
        if ($data['electrity'] > 0) $data['electrity'] = $data['electrity'] / 100;
        if ($data['water'] > 0) $data['water'] = $data['water'] / 100;
        if ($data['charge'] > 0) $data['charge'] = $data['charge'] / 100;
        return SendSuccess("success", $data);
    }

    /**
     * 选择商户店铺
     */
    public function selectBrand()
    {
//        $this->merchant_id = 3;
        $mobile = (new MerchantModel())->where('id', $this->merchant_id)->value('mobile');
        $info = (new MerchantModel())->where('mobile', $mobile)->where('status', 1)->select();
        return SendSuccess('success', $info);
    }

    /**
     * 获取商户需要上报的列表
     */
    public function TaskList()
    {
        $result = MerchantModel::where(['id' => $this->merchant_id])->field('id,task_id')->find();
        if (empty($result)) {
            return SendError("该用户不存在");
        }
        $task = explode(',', $result['task_id']);
        if (empty($task[0])) {
            return SendError('请去配置商户需要上报的任务');
        }
        $systemTask = Task::field('id as type,name')->where(['type_staff' => 1])->select()->toArray();
        $taskList = [];
        foreach ($systemTask as $key => $row) {
            foreach ($task as $kk => $rows) {
                if ($row['type'] == $rows) {
                    unset($task[$kk]);
                    $taskList[] = $systemTask[$key];
                }

            }
        }
        return SendSuccess('success', $taskList);
    }

    /**
     *通过task中type值,查询用户的组件
     */
    public function TaskDetail()
    {
        $id = $this->request->param('type');
        $TaskInfo = Task::field('id as type,name,text')->where('id', $id)->find();
        if (empty($TaskInfo)) {
            return SendError('任务详情不存在');
        } else {
            if (!empty($TaskInfo['text'])) {
                $TaskInfo['text'] = json_decode($TaskInfo['text'], true);
                $arrData = $TaskInfo['text'];
                foreach ($arrData as $k => $v) {
                    $arrData[$k]['image'] = '';
                    $arrData[$k]['value'] = '';
                }
                $TaskInfo['text'] = $arrData;
            }

        }
        return SendSuccess('success', $TaskInfo);
    }

    // 代缴费项查询
    public function toPayCost()
    {
        $list = Cost::where(['merchant_id' => $this->merchant_id, 'pay_status' => 0, 'is_void' => 1])
            ->with(['costType' => function ($e) {
                $e->field('id,cost_name,type')->find();
            }])
            ->field('id,type,amount,real_amount,create_time,cost_type_id')
            ->select();

        if ($list->isEmpty()) {
            return SendSuccess("success", []);
        } else {
            $list = $list->toArray();
            foreach ($list as $key => $value) {
                $list[$key]['create_time'] = date('Y/m/d', $value['create_time']);
            }
            return SendSuccess("success", $list);
        }

    }

    //代缴费列表
    public function toPayCostList()
    {
        $status = $id = $this->request->param('status');
        if (!in_array($status, [0, 1])) {
            return SendError("参数错误");
        }
        $list = Cost::where(['merchant_id' => $this->merchant_id, 'pay_status' => $status, 'is_void' => 1])
            ->with(['costType' => function ($e) {
                $e->field('id,cost_name as name,type')->find();
            }])
            ->field('id,amount,all_amount,pay_amount,create_time,type,cost_type_id,pay_status,electrity_type')
            ->select()
            ->toArray();
        foreach ($list as $key => $value) {
            $list[$key]['create_time'] = date('Y/m/d', strtotime($value['create_time']));
            $list[$key]['costType']['name'] = $list[$key]['costType']['cost_name'];
//            if ($value['type'] == 3) {
//                $list[$key]['costType']['name'] = $value['cost_type_id'] == 1 ? '员工证' : '施工证';
//            }
        }
        return SendSuccess("success", $list);
    }

    //代缴费列表
    public function HomeList()
    {
        $type = $this->request->param('type');
        if (empty($type)) {
            return SendError('请传入类型');
        }
        if ($type == 1) {
            $where[] = ['type', 'not in', [4, 5]];
        } else {
            $where[] = ['type', 'in', [4, 5]];
        }
        $list = Cost::where(['merchant_id' => $this->merchant_id, 'pay_status' => 0, 'is_void' => 1])
            ->with(['costType' => function ($e) {
                $e->field('id,cost_name,type')->find();
            }])
            ->where($where)
            ->field('id,amount,all_amount,pay_amount,contract_code,create_time,type,cost_type_id,pay_status,start_time,end_time,electrity_type')
            ->select()
            ->toArray();
        foreach ($list as $key => $value) {
            $list[$key]['create_time'] = date('Y/m/d', $value['create_time']);
            $list[$key]['start_time'] = date('Y/m/d', $value['start_time']);
            $list[$key]['end_time'] = date('Y/m/d', $value['end_time']);
            $list[$key]['costType']['name'] = $list[$key]['costType']['cost_name'];
            $list[$key]['checked'] = false;
        }
        return SendSuccess("success", $list);
    }

    //待缴费订单详情
    public function toPayCostDetail()
    {
        $id = $this->request->param('id');
        if (empty($id)) {
            return SendError("参数错误");
        }
        try {
            $list = Cost::where(['merchant_id' => $this->merchant_id, 'id' => $id])
                ->with(['costType' => function ($e) {
                    $e->field('id,cost_name as name,type')->find();
                }, 'merchant' => function ($e) {
                    $e->field('id,name,merchant_sn,balance,company')->find();
                }, 'ticketConfig' => function ($es) {
                    $es->find();
                }])
                ->field('id,subject_id,remark,add_user,ticket_id,contract_code,all_amount,amount,pay_amount,merchant_id,order_sn,amount,real_amount,type,create_time,cost_type_id,remark,pay_status,start_time,end_time,electrity_type')
                ->find();
//            $list = Cost::where(['merchant_id' => $this->merchant_id, 'id' => $id])
//                ->with(['costType' => function ($e) {
//                    $e->field('id,cost_name as name,type')->find();
//                }, 'merchant' => function ($e) {
//                    $e->field('id,name,merchant_sn,balance,company')->find();
//                }])->with(['ticket'])->find();
            if (empty($list)) {
                return SendError("没有该订单");
            }
            $list = $list->toArray();
            $list['create_time'] = date('Y/m/d', $list['create_time']);
            $pay_type = (new SubjectList())->where('score', 1)->find();
            $service_charge = round($pay_type['rate'] / 1000 * $list['real_amount']);
            $list['poundage'] = $service_charge;
            $list['real_amount'] += $list['real_amount'];
            if(!empty($list['ticketConfig'])){
                $list['ticketConfig']['content'] = html_entity_decode($list['ticketConfig']['content'], ENT_QUOTES);
            }
//            }
            if(isset($list['ticket']['name'])){
                $list['costType']['cost_name'] = $list['ticketConfig']['name'];
            }
            if ($list['type'] == 3) {
                $list['costType']['cost_name'] = $list['cost_type_id'] == 1 ? '员工证' : '施工证';
            }
            return SendSuccess("success", $list);
        } catch (\Exception $exception) {
            return SendError("没有该订单{$exception->getMessage()}");
        }

    }

    /**
     * 获取入离场抄表列表
     */
    public function getReadingList()
    {
        $merchant_id = $this->merchant_id;
        $MerchantReadingLog = new MerchantReadingLog();
        $list = $MerchantReadingLog->with(['watch'])->where('merchant_id', $merchant_id)->whereOr('new_merchant_id', $merchant_id)->select();
        if ($list->isEmpty()) {
            return SendSuccess('', []);
        }
        $list = $list->toArray();
        foreach ($list as $k => $v) {
            $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
        }
        return SendSuccess('success', $list);
    }

    /**
     * 商户确认
     */
    public function ReadingConfirm()
    {
        $id = $this->request->param('id');
        if (empty($id)) {
            return SendError('请传入id');
        }
        $MerchantReadingLog = new MerchantReadingLog();
        $info = $MerchantReadingLog->find($id);
        if (empty($info)){
            return SendError('信息不存在');
        }
        $result = $MerchantReadingLog->update(['is_read' => 1], ['id' => $id]);
        $watchInfo = new WatchMaintain();
        if($info['in_type']==2){
            $watchInfo->where(['pointId' => $info['pointId']])->update(['merchant_id' => 1918]);
        }
        if($info['in_type']==1){
            (new WatchMaintain())->where(['pointId' => $info['pointId']])->update(['merchant_id' => $info['new_merchant_id']]);
        }
        if ($result) {
            return SendSuccess('确认成功');
        }
        return SendError('确认失败,请重试');
    }

    /**
     * 获取商户余额
     */
    public function myBalance()
    {
        $merchant_id = $this->merchant_id;
        $balance = MerchantModel::where('id', $merchant_id)->value('balance');
        $data['balance'] = $balance / 100;
        $monthModel = new MerchantMonthMoney();
        $MonthInfo = $monthModel->where(['merchant_id' => $merchant_id])->where('dataTime', date('Y-m'))->find();
        $data['money'] = isset($MonthInfo['money']) ? $MonthInfo['money'] / 100 : 0;
        $data['water_money'] = isset($MonthInfo['water_money']) ? $MonthInfo['water_money'] / 100 : 0;
        $data['dataTime'] = isset($MonthInfo['dataTime']) ? $MonthInfo['dataTime'] : date('Y-m');
        $MonthList = $monthModel->where(['merchant_id' => $merchant_id])->where('dataTime', '<>', date('Y-m'))->order('dataTime', 'desc')->select();
        if (!empty($MonthList)) {
            foreach ($MonthList as $k => $v) {
                $MonthList[$k]['use_yue'] = $v['use_yue'] / 100;
                $MonthList[$k]['water_money'] = $v['water_money'] / 100;
                $MonthList[$k]['money'] = $v['money'] / 100;
            }
        }
        $data['MonthList'] = $MonthList;
        return SendSuccess('succes', $data);
    }

    public function balanceAdd()
    {
        $param = $this->request->param();
        $merchant_id = $this->merchant_id;
        $balanceAudit = new BalanceAudit();
        $code = (new \app\common\model\tang\Merchant())->where('id', $merchant_id)->value('code');
        if (empty($param['image'])) {
            return SendError('请传入转账凭证');
        }
        if (empty($param['amount']) || $param['amount'] < 0) {
            return SendError('请输入转账金额或大于0的金额');
        }
        if (empty($param['back_number'])) {
            return SendError('请选择转入银行账户信息');
        }
        if (empty($param['up_time'])) {
            return SendError('请选择转账日期');
        }
        $balanceAudit->merchant_id = $merchant_id;
        $balanceAudit->back_number = $param['back_number'];
        $balanceAudit->create_time = time();
        $balanceAudit->amount = $param['amount'] * 100;
        $balanceAudit->image = $param['image'];
        $balanceAudit->code = $code;
        $balanceAudit->up_time = $param['up_time'];
        $result = $balanceAudit->save();
        if ($result) {
            return SendSuccess('添加成功');
        }
        return SendError('添加失败,请重试');
    }

    public function balanceList()
    {
        $param = $this->request->param();
        if (empty($param['status']) && $param['status'] != 0) {
            return SendError('请传入审核状态');
        }
        $balanceAudit = new BalanceAudit();
        $merchant_id = $this->merchant_id ?? 120;
        $where = [];
        $where['merchant_id'] = $merchant_id;
        if ($param['status'] != -1) {
            $where['status'] = $param['status'];
        }
        $balanceList = $balanceAudit->where($where)->order('id desc')->select();
        if ($balanceList->isEmpty()) {
            return SendSuccess('success', []);
        } else {
            $balanceList = $balanceList->toArray();
            foreach ($balanceList as $key => $val) {
                if ($val['create_time']) {
                    $balanceList[$key]['create_time'] = date('Y-m-d H:i:s', $val['create_time']);
                }
                if ($val['suggest_time']) {
                    $balanceList[$key]['suggest_time'] = date('Y-m-d H:i:s', $val['suggest_time']);
                }
            }
            return SendSuccess('success', $balanceList);
        }
    }

    /**
     *微信支付
     */

    public function toPayCostPay()
    {
        $id = $this->request->param('id');
        if (empty($id)) {
            return SendError("参数错误");
        }
        $list = Cost::where(['merchant_id' => $this->merchant_id, 'pay_status' => 0, 'is_user' => 0, 'id' => $id])
            ->field('id,merchant_id,order_sn,real_amount,amount,create_time,cost_type_id,remark')
            ->find();
        if (empty($list)) {
            return SendError("暂无订单");
        }
        $order_sn = OrderSn();
        Cost::where(['merchant_id' => $this->merchant_id])
            ->where('id', $list['id'])
            ->update(['order_sn' => $order_sn]);
        try {
            $data = [
                "mch_id" => config('wxapp.pay_mch_id'),
                "out_trade_no" => $order_sn,
                'sub_appid' => config('wxapp.app_id'),
                "sub_mchid" => config('wxapp.pay_sub_mch_id'),
                "total_fee" => $list['amount'],
                "body" => '订单支付',
                'sub_openid' => $this->openid,
                'notify_url' => 'https://zdwy.kelimx.com/api/cost/notify'
            ];
            $result = RequestServer('pay/wechatPay/BasicPay/miniProgramNoProfitSharing', $data, config('wxapp.pay_mch_id'));
            return SendSuccess("success", $result);
        } catch (\Exception $exception) {
            return SendError($exception->getMessage());
        }
    }

    /**
     * 部分缴费付款
     */
    public function sectionPay()
    {
        $id = $this->request->param('id');
        $amount = $this->request->param('amount');
        if (empty($id)) {
            return SendError("参数错误");
        }
        if (empty($amount) || $amount < 0) {
            return SendError("参数错误");
        }
        $list = Cost::where(['merchant_id' => $this->merchant_id, 'pay_status' => 0, 'id' => $id])
            ->field('id,merchant_id,order_sn,real_amount,amount,create_time,cost_type_id,remark')
            ->find();
        if (empty($list)) {
            return SendError("暂无订单");
        }
        if ($amount * 100 > $list['amount']) {
            return SendError("请输入小于或等于账单的金额");
        }
        $order_sn = OrderSn();
        Cost::where(['merchant_id' => $this->merchant_id])
            ->where('id', $list['id'])
            ->update(['order_sn' => $order_sn]);
        try {
            $data = [
                "mch_id" => config('wxapp.pay_mch_id'),
                "out_trade_no" => $order_sn,
                'sub_appid' => config('wxapp.app_id'),
                "sub_mchid" => config('wxapp.pay_sub_mch_id'),
                "total_fee" => $amount * 100,
                "body" => '订单支付',
                'sub_openid' => $this->openid,
                'notify_url' => 'https://zdwy.kelimx.com/api/cost/notify'
            ];
            $result = RequestServer('pay/wechatPay/BasicPay/miniProgramNoProfitSharing', $data, config('wxapp.pay_mch_id'));
            return SendSuccess("success", $result);
        } catch (\Exception $exception) {
            return SendError($exception->getMessage());
        }
    }

    /**
     *部分缴费列表
     */
    public function sectionPayList()
    {
        $id = $this->request->param('id');
        if (empty($id)) {
            return SendError("参数错误");
        }
        $all_amount = (new Cost())->where(['id' => $id])->value('all_amount');
        $list = (new CostSectionPay())->where('cost_id', $id)->select();
        if ($list->isEmpty()) {
            return SendSuccess('success', []);
        }
        $data['list'] = $list;
        $data['all_amount'] = $all_amount / 100;
        return SendSuccess('success', $data);
    }

    /**
     * 合并多个订单支付
     */
    public function CostPay()
    {
        $ids = $this->request->param('ids/a');
        if (empty($ids)) {
            return SendError('订单不能为空');
        }
        $merchantStatus = MerchantModel::where(['id' => $this->merchant_id])->value('status');
        if ($merchantStatus == -1) {
            return SendError("商户被冻结,暂不能支付");
        }
        $list = Cost::where(['merchant_id' => $this->merchant_id, 'pay_status' => 0])
            ->whereIn('id', $ids)
            ->field('id,merchant_id,order_sn,real_amount,amount,create_time,cost_type_id,remark')
            ->order('id desc')
            ->select();
        if ($list->isEmpty()) {
            return SendError("暂无订单");
        }
        $real_amount = 0;
        $service_charge = 0;
        $pay_type = (new SubjectList())->where('score', 1)->find();//计算微信支付手续费
        $merge_sn = OrderSn();
        foreach ($list as $row) {
//            $service_charge += round($pay_type['rate'] / 1000 * $row['amount']);
//            $real_amount += $row['real_amount'];
            $real_amount += $row['amount'];
        }
        Cost::where(['merchant_id' => $this->merchant_id, 'pay_status' => 0])
            ->whereIn('id', $ids)
            ->update(['merge_sn' => $merge_sn]);
        try {
            $data = [
                "mch_id" => config('wxapp.pay_mch_id'),
                "out_trade_no" => $merge_sn,
                'sub_appid' => config('wxapp.app_id'),
                "sub_mchid" => config('wxapp.pay_sub_mch_id'),
                "total_fee" => $real_amount,
                "body" => '多笔费用订单支付',
                'sub_openid' => $this->openid,
                'notify_url' => 'https://zdwy.kelimx.com/api/cost/mergenotify'
            ];
            $result = RequestServer('pay/wechatPay/BasicPay/miniProgramNoProfitSharing', $data, config('wxapp.pay_mch_id'));
            return SendSuccess("success", $result);
        } catch (\Exception $exception) {
            return SendError($exception->getMessage());
        }
    }

    /**
     * 获取商户宝权限
     */
    public function getRole()
    {
        $Marketing = new MarketingService();
        $Member = new MemberService();
        $info = (new MerchantModel())->where('id', $this->merchant_id)->value('member_id');
        $data['Marketing'] = $Marketing->getRole();
        if (!empty($info)) {
            $data['Member'] = $Member->role_lists($info);
        } else {
            $data['Member'] = [];
        }
        return SendSuccess('success', $data);
    }

    /**
     * 余额支付
     * @return \think\response\Json
     */
    public function balancePay()
    {
        $id = $this->request->param('id');
        $money = $this->request->param('money');
        $money = $money*100;
        if (empty($id)) {
            return SendError("参数错误");
        }
        if (empty($money)) {
            return SendError("请传入金额");
        }
        $HDService = new HaiDing();
        $data = Cost::where(['id' => $id])
            ->with(['merchant' => function ($e) {
                $e->find();
            }])
            ->find();
        if (empty($data)) {
            return SendError("没有该订单");
        }
        $data = $data->toArray();
        if ($data['pay_status'] != 0) {
            return SendError("该订单已支付");
        }
        if( $data['merchant']['balance']<0){
            return SendError("余额为负数,请充值");
        }
        if ($money > $data['merchant']['balance']) {
            return SendError("最多可输入".$data['merchant']['balance']/100);
        }
        $return_billid = 0;
        Db::startTrans();
        try {
            if ($money >= $data['amount']) {
                $ticket = (new \app\common\model\tang\RepairRecord())->where(['cost_id'=>$data['id']])->find();
                if(!empty($ticket)){
                    (new \app\common\model\tang\RepairRecord())->where(['cost_id'=>$data['id']])->update(['status'=>3]);
                }
                $pay_status = 1;
                $amount = 0;
                $balance_amount = 0;
                $pay_amount =$data['amount'];
                $bill = getBill();
                $pay_time = date('Y-m-d H:i:s');
            }else{
                $amount = bcsub($data['amount'],$money);
                $pay_amount = bcadd($money,$data['pay_amount']);
                $balance_amount = $pay_amount;
                $bill = '';
                $pay_status = 0;
                $pay_time = '';
            }
            if (!empty($data['billid'])) {
                $payInfo['direction'] = 1;
                $payInfo['paymentMethod'] = 'APP';
                $payInfo['paymentOrderId'] = $data['order_sn'];
                $payInfo['dealer'] = [
                    'uuid' => '8a0293a988c2d2120188c32b25870098',
                    'code' => 'mianbei',
                    'name' => '米安贝',
                ];
                $payInfo['paymentDate'] = date('Y-m-d H:i:s', time());
                $payInfo['incomeDate'] = date('Y-m-d H:i:s', time());
                $payInfo['remark'] = '微信小程序收款';
                $payInfo['sourceType'] = 'cre_other';
                $payInfo['lines'] = [
                    [
                        'accId' => $data['billid'],
                        'total' => $pay_amount / 100,
                        'paymentType' => [
                            'uuid' => '8a0289aa736f21880173bc84e7a36fa5',
                            'code' => '003',
                            'name' => '预收冲扣',
                        ],
                        'bankCode' => '',
                        'poundage' => ''
                    ]
                ];
                $result = $HDService->payInfo($payInfo);
                $costLogInfo = new CostLog();
                $costLog['cost_id'] = $data['id'];
                $costLog['request_info'] = json_encode($payInfo);
                $costLog['responce_info'] = json_encode($result);
                $costLog['happen_time'] = date('Y-m-d H:i:s', time());
                $costLog['create_time'] = time();
                $costLog['update_time'] = time();
                $costLogInfo->save($costLog);
                if (isset($result['billNumber'])) {
                    $return_billid = $result['billNumber'];
                }
            }
            if (in_array($data['cost_type_id'], [51, 52, 53, 54, 55, 56, 57])) {
                $costTypeInfo = [];
                $costTypeInfo = (new CostType())->where('id', $data['cost_type_id'])->find();
                $receipt['unitCode'] = $data['merchant']['store_code'];
                $receipt['counterpartCode'] = $data['merchant']['tenant_code'];
                $receipt['dealer'] = [
                    'uuid' => '8a0293a988c2d2120188c32b25870098',
                    'code' => 'mianbei',
                    'name' => '米安贝',
                ];
                $receipt['paymentOrderId'] = $data['order_sn']; //订单编号
                $receipt['contractCode'] = $data['merchant']['code'];//合同号
                $receipt['paymentTypeCode'] = '003'; //付款方式代码
                $receipt['depositDate'] = date('Y-m-d H:i:s', time()); //预存日期（收款日期）
                $receipt['accountDate'] = date('Y-m-d H:i:s', time());//记账日期
                $receipt['bankCode'] = '';//银行代码
                $receipt['counterContact'] = '';//对方联系人
                $receipt['bankFlowRemark'] = '';
                $receipt['lines'] = [
                    [
                        'subjectCode' => $costTypeInfo['cost_type_id'],
                        'amount' => $pay_amount / 100,
                        'remark' => '米安贝缴费'
                    ]
                ];
                $result = $HDService->deposit($receipt);
                $costLogInfo = new CostLog();
                $costLog['cost_id'] = $data['id'];
                $costLog['request_info'] = json_encode($receipt);
                $costLog['responce_info'] = json_encode($result);
                $costLog['happen_time'] = date('Y-m-d H:i:s', time());
                $costLog['create_time'] = time();
                $costLog['update_time'] = time();
                $costLogInfo->save($costLog);
                if (isset($result['billNumber'])) {
                    $return_billid = $result['billNumber'];
                }
            }
            // 记录日志扣减log
            BalanceLog::create([
                'openid' => $this->openid,
                'mobile' => $this->mobile,
                'is_top_up' => 2,
                'merchant_id' => $data['merchant']['id'],
                'order_sn' => $data['order_sn'],
                'edit' => 2,
                'type' => 3,
                'amount' => $money,
                'remark' => '商户使用余额支付'
            ]);
            $section = new CostSectionPay(); //部分缴费
            $section->merchant_id = $data['merchant_id'];
            $section->transaction_id = '';
            $section->all_amount = $data['all_amount'];
            $section->cost_id = $data['id'];
            $section->amount = $pay_amount;
            $section->balance_amount = $amount;
            $section->create_time = time();
            $section->update_time = time();
            $section->type = 2;
            $section->save();

            $updata = [
                'pay_status' => $pay_status,
                'subject_id' => 2,//余额支付
                'pay_amount' => $pay_amount,
                'openid' => $this->openid,
                'amount' => $amount,
                'return_billid' => $return_billid,
                'bill_no' => $bill,
                'pay_time' => $pay_time,
            ];
            $payLog = new PayInfo();
            $payLog->amount = $amount;
            $payLog->cost_id = $data['id'];
            $payLog->create_time = time();
            $payLog->type = 2;
            $payLog->save();
            //  改状态
            Cost::update($updata, ['id' => $id]);
            // 更新余额
            upMerchantAuto($this->merchant_id);
            Db::commit();
            return SendSuccess("余额支付成功", []);
        } catch (\Exception $exception) {
            Db::rollback();
            return SendError($exception->getMessage());
        }
    }

    /**
     * 批量余额缴费
     */
    public function MergeBalancePay()
    {
        $ids = $this->request->param('ids/a');
        if (empty($ids)) {
            return SendError('订单不能为空');
        }
        $list = Cost::whereIn('id', $ids)
            ->with(['merchant', 'costType'])
            ->select();
        if ($list->isEmpty()) {
            return SendError("暂无订单");
        }
        $list = $list->toArray();
        $merchantInfo = (new MerchantModel)->where('id', $this->merchant_id)->find()->toArray();
        $real_amount = 0;
        $merge_sn = OrderSn();
        foreach ($list as $row) {
            $real_amount += $row['amount'];
        }
        if ($real_amount > $merchantInfo['balance']) {
            return SendError("余额不足");
        }
        Db::startTrans();
        try {
            foreach ($list as $k => $v) {
                $ticket = (new \app\common\model\tang\RepairRecord())->where(['cost_id' => $v['id']])->find();
                if (!empty($ticket)) {
                    (new \app\common\model\tang\RepairRecord())->where(['cost_id' => $v['id']])->update(['status' => 3]);
                }
                if (!empty($v['billid'])) {
                    $payInfo['direction'] = 1;
                    $payInfo['paymentMethod'] = 'APP';
                    $payInfo['paymentOrderId'] = $v['order_sn'];
                    $payInfo['dealer'] = [
                        'uuid' => '8a0293a988c2d2120188c32b25870098',
                        'code' => 'mianbei',
                        'name' => '米安贝',
                    ];
                    $payInfo['paymentDate'] = date('Y-m-d H:i:s', time());
                    $payInfo['incomeDate'] = date('Y-m-d H:i:s', time());
                    $payInfo['remark'] = '微信小程序收款';
                    $payInfo['sourceType'] = 'cre_other';
                    $payInfo['lines'] = [
                        [
                            'accId' => $v['billid'],
                            'total' => $v['amount'] / 100,
                            'paymentType' => [
                                'uuid' => '8a0289aa736f21880173bc84e7a36fa5',
                                'code' => '003',
                                'name' => '预收冲扣',
                            ],
                            'bankCode' => '',
                            'poundage' => ''
                        ]
                    ];
                    $HDService = new HaiDing();
                    $result = $HDService->payInfo($payInfo);
                    $costLogInfo = new CostLog();
                    $costLog['cost_id'] = $v['id'];
                    $costLog['request_info'] = json_encode($payInfo);
                    $costLog['responce_info'] = json_encode($result);
                    $costLog['happen_time'] = date('Y-m-d H:i:s', time());
                    $costLog['create_time'] = time();
                    $costLog['update_time'] = time();
                    $costLogInfo->save($costLog);
                    if (isset($result['billNumber'])) {
                        $costModel['return_billid'] = $result['billNumber'];
                    }
                }
                if (in_array($v['cost_type_id'], [51, 52, 53, 54, 55, 56, 57])) {
                    $costTypeInfo = [];
                    $costTypeInfo = (new CostType())->where('id', $v['cost_type_id'])->find();
                    $receipt['unitCode'] = $v['merchant']['store_code'];
                    $receipt['counterpartCode'] = $v['merchant']['tenant_code'];
                    $receipt['dealer'] = [
                        'uuid' => '8a0293a988c2d2120188c32b25870098',
                        'code' => 'mianbei',
                        'name' => '米安贝',
                    ];
                    $receipt['paymentOrderId'] = $v['order_sn']; //订单编号
                    $receipt['contractCode'] = $v['merchant']['code'];//合同号
                    $receipt['paymentTypeCode'] = '003'; //付款方式代码
                    $receipt['depositDate'] = date('Y-m-d H:i:s', time()); //预存日期（收款日期）
                    $receipt['accountDate'] = date('Y-m-d H:i:s', time());//记账日期
                    $receipt['bankCode'] = '';//银行代码
                    $receipt['counterContact'] = '';//对方联系人
                    $receipt['bankFlowRemark'] = '';
                    $receipt['lines'] = [
                        [
                            'subjectCode' => $costTypeInfo['cost_type_id'],
                            'amount' => $v['amount'] / 100,
                            'remark' => '米安贝缴费'
                        ]
                    ];
                    $HDService = new HaiDing();
                    $result = $HDService->deposit($receipt);
                    $costLogInfo = new CostLog();
                    $costLog['cost_id'] = $v['id'];
                    $costLog['request_info'] = json_encode($receipt);
                    $costLog['responce_info'] = json_encode($result);
                    $costLog['happen_time'] = date('Y-m-d H:i:s', time());
                    $costLog['create_time'] = time();
                    $costLog['update_time'] = time();
                    $costLogInfo->save($costLog);
                    if (isset($result['billNumber'])) {
                        $costModel['return_billid'] = $result['billNumber'];
                    }
                }
                $sendMerchant = [];
                if (!empty($v['merchant']) && !empty($v['costType'])) {
                    $sendMerchant['merchant_name'] = $v['merchant']['company'];
                    $sendMerchant['code'] = $v['merchant']['code'];
                    $sendMerchant['amount'] = $v['amount'] / 100;
                    $sendMerchant['cost_name'] = $v['costType']['cost_name'];
                    $sendMerchant['openid'] = $this->openid;
                    (new message())->pay_success($sendMerchant);
                }
                $costModel['pay_status'] = 1;
                $costModel['openid'] = $this->openid;
                $costModel['pay_amount'] = $v['amount'];
                $costModel['amount'] = 0;
                $costModel['subject_id'] = 2;
                $costModel['bill_no'] = getBill();
                $costModel['pay_time'] = date('Y-m-d H:i:s', time());
                (new Cost())->update($costModel, ['id' => $v['id']]);

                $section = new CostSectionPay(); //部分缴费
                $section->merchant_id = $v['merchant_id'];
                $section->transaction_id = '';
                $section->all_amount = $v['all_amount'];
                $section->cost_id = $v['id'];
                $section->amount = $v['amount'];
                $section->balance_amount = 0;
                $section->create_time = time();
                $section->update_time = time();
                $section->type = 2;
                $section->save();

            }
            BalanceLog::create([
                'openid' => $this->openid,
                'mobile' => $this->mobile,
                'is_top_up' => 2,
                'merchant_id' => $this->merchant_id,
                'order_sn' => count($list) > 1 ? $merge_sn : $list[0]['order_sn'],
                'edit' => 2, //余额支付
                'amount' => $real_amount,
                'type' => 3,
                'remark' => '商户使用余额支付'
            ]);



            $payLog = new PayInfo();
            $payLog->amount = $real_amount;
            $payLog->cost_id = implode(',', $ids);
            $payLog->create_time = time();
            $payLog->type = 2;
            $payLog->save();
            // 更新余额
            upMerchantAuto($this->merchant_id);
            Db::commit();
            return SendSuccess("余额支付成功", []);
        } catch (\Exception $exception) {
            Db::rollback();
            return SendError($exception->getMessage());
        }
    }

    /**
     * 上传票据支付
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function uploadBillPay()
    {
        $id = $this->request->param('id');
        $image = $this->request->param('image');
        $upTime = $this->request->param('up_time');
        $amount = $this->request->param('amount');
        $backNumber = $this->request->param('back_number');
        if (empty($id)) {
            return SendError("参数错误");
        }
        if (empty($image) || empty($upTime) || empty($amount) || empty($backNumber)) {
            return SendError("参数错误");
        }
        $data = Cost::where(['merchant_id' => $this->merchant_id, 'id' => $id])
            ->with(['merchant' => function ($e) {
                $e->field('id,name,merchant_sn,balance')->find();
            }])
            ->where('start_time', '>', strtotime(date('2022-08-31 00:00:00')))
            ->field('id,merchant_id,amount,mobile,real_amount,order_sn,type,create_time,cost_type_id,remark,pay_status')
            ->find();
        if (empty($data)) {
            return SendError("没有该订单");
        }
        $data = $data->toArray();
        if ($data['pay_status'] != 0) {
            return SendError("该订单已支付");
        }
        if (empty($data['mobile'])) {
            $updata['mobile'] = $this->mobile;
        }
        $costAudit = new CostAudit();
        $audit['cost_id'] = $id;
        $audit['merchant_id'] = $this->merchant_id;
        $audit['amount'] = $data['amount'];
        $audit['in_amount'] = $amount * 100;//用户输入金额
        $audit['back_number'] = $backNumber;//银行账号
        $audit['up_time'] = $upTime;//缴费日期
        $audit['create_time'] = time();
        $audit['other_certificate'] = $image;
        $costAudit->save($audit);
        $updata = [
            'pay_status' => 3, // 票据审核
            'order_sn' => OrderSn(), // 票据审核冲洗生成账单号
            'openid' => $this->openid,
            'other_certificate' => $image,
            'subject_id' => 2
        ];
        $bool = Cost::update($updata, ['id' => $id]);
        if (!$bool) {
            return SendError('上传票据付款失败');
        }
        return SendSuccess("上传票据付款成功", []);
    }

    /**
     * 批量上传票据支付
     */
    public function uploadBillPays()
    {
        $ids = $this->request->param('ids/a');
        $image = $this->request->param('image');
        $upTime = $this->request->param('up_time');
        $amounts = $this->request->param('amount');
        $backNumber = $this->request->param('back_number');
        if (empty($ids)) {
            return SendError("参数错误");
        }
        if (empty($image) || empty($upTime) || empty($amounts) || empty($backNumber)) {
            return SendError("参数错误");
        }
        Db::startTrans();
        try {
            $list = Cost::where(['merchant_id' => $this->merchant_id, 'pay_status' => 0])
                ->whereIn('id', $ids)
                ->field('id,merchant_id,order_sn,real_amount,amount,create_time,cost_type_id,remark,pay_status')
                ->select();
            if ($list->isEmpty()) {
                return SendError("暂无订单");
            }
            $amount = 0;
            foreach ($list as $k => $v) {
                $amount += $v['amount'];
                $updata = [
                    'pay_status' => 3, // 票据审核
                    'openid' => $this->openid,
                    'other_certificate' => $image,
                    'subject_id' => 2,
                    'order_sn' => OrderSn(),
                ];
                Cost::update($updata, ['id' => $v['id']]);
            }
            $costAudit = new CostAudit();
            $audit['cost_id'] = implode(',', $ids);
            $audit['merchant_id'] = $this->merchant_id;
            $audit['amount'] = $amount;
            $audit['in_amount'] = $amounts * 100;//用户输入金额
            $audit['back_number'] = $backNumber;//银行账号
            $audit['up_time'] = $upTime;//缴费日期
            $audit['create_time'] = time();
            $audit['other_certificate'] = $image;
            $result = $costAudit->save($audit);
            if ($result) {
                Db::commit();
                return SendSuccess('上传票据付款成功', []);
            } else {
                return SendError('系统繁忙');
            }
        } catch (\Exception $exception) {
            Db::rollback();
            return SendError($exception->getMessage());
        }
    }

    /**
     * 切换门店
     */
    public function switchStores()
    {
        $id = $this->request->param('id');
        if (empty($id)) {
            return SendError('请传入需要切换的门店ID');
        }
        $merchantInfo = (new MerchantModel())->where(['id' => $id, 'mobile' => $this->mobile])->find();
        if (empty($merchantInfo)) {
            return SendError('切换的门店不存在');
        }
        (new MerchantModel())->update(['openid' => $this->openid], ['id' => $id]);
        $jwtAuth = JwtService::getInstance();
        $token = $jwtAuth->setOpenid($this->openid)
            ->setUid($id)
            ->setMobile($this->mobile)
            ->encode()
            ->getToken();
        return SendSuccess('切换门店成功', $token);
    }

    /**
     * 补充资料
     */
    public function addExtra()
    {
        $data = $this->request->param();
        $data['merchant_id'] = $this->merchant_id;
        $isfirst = (new MerchantExtra())->where($data)->find();
        if ($isfirst->isEmpty()) {
            $result = (new MerchantExtra())->save($data);
            if ($result) {
                return SendSuccess('添加成功');
            }
            return SendError('添加失败');
        } else {
            return SendError('您已提交过了');
        }
    }

    /**
     * 更新商户信息
     */
    public function updateInfo()
    {
        $param = $this->request->param();
        $result = MerchantModel::update($param, ['id' => $this->merchant_id]);
        if ($result) {
            return SendSuccess('success');
        } else {
            return SendError('系统繁忙');
        }
    }

    /**
     * 开票列表新
     */
    public function invoiceListNew()
    {
        $list = (new Invoice())->with(['cost'])->where('merchant_id', $this->merchant_id)->order('id desc')->select();
        if (empty($list)) {
            return SendSuccess('success', []);
        }
        $list = $list->toArray();
        foreach ($list as $k => $v) {
            $ids = [];
            $ids = explode(',', $v['costId']);
            $list[$k]['money'] = (new Cost())->whereIn('id', $ids)->sum('all_amount');
            $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['createTime']);
        }
        return SendSuccess('success', $list);

    }

    /**
     * 开票详情
     */
    public function invoiceDetailNew()
    {
        $id = $this->request->param('id');
        if (empty($id)) {
            return SendError('请传入id');
        }
        $list = (new Invoice())->find($id);
        if (empty($list)) {
            return SendError('发票不存在');
        }
        $ids = explode(',', $list['costId']);
        $costInfo = (new Cost())->with(['costType'])->whereIn('id', $ids)->field('id,order_sn,cost_type_id,all_amount,start_time,end_time')->select()->toArray();
        foreach ($costInfo as $kk => $vv) {
            $costInfo[$kk]['start_time'] = date('Y-m-d', $vv['start_time']);
            $costInfo[$kk]['end_time'] = date('Y-m-d', $vv['end_time']);
        }
        $list['money'] = (new Cost())->whereIn('id', $ids)->sum('all_amount');
        $list['costInfo'] = $costInfo;
        if ($list->isEmpty()) {
            return SendSuccess('success', []);
        } else {
            return SendSuccess('success', $list->toArray());
        }
    }

    /**
     * 查看
     */
    public function seeExtra()
    {
        $where['merchant_id'] = $this->merchant_id;
        $result = (new MerchantExtra())->where($where)->find();
        if (empty($result)) {
            return SendSuccess('暂无数据', []);
        }
        return SendSuccess('获取成功', $result);
    }

    public function topUp()
    {
        $amount = $this->request->param('amount');
        if (empty($amount)) {
            return SendError("参数错误");
        }
        $order_sn = OrderSn();
        try {
            $data = [
                "mch_id" => config('wxapp.pay_mch_id'),
                "out_trade_no" => $order_sn,
                'sub_appid' => config('wxapp.app_id'),
                "sub_mchid" => config('wxapp.pay_sub_mch_id'),
                "total_fee" => $amount * 100,
                "body" => '商户预充值',
                'sub_openid' => $this->openid,
                'notify_url' => 'https://zdwy.kelimx.com/api/top_up/notify'
            ];
            $result = RequestServer('pay/wechatPay/BasicPay/miniProgramNoProfitSharing', $data, config('wxapp.pay_mch_id'));
            $bool = BalanceLog::create([
                'openid' => $this->openid,
                'mobile' => $this->mobile,
                'order_sn' => $order_sn,
                'amount' => $amount * 100,
                'service_charge' => 0,
                'merchant_id' => $this->merchant_id,
                'is_top_up' => 1,
                'edit' => 1,
                'type' => 1,
                'status' => 0,
                'remark' => '微信充值余额'
            ]);
            if (!$bool) {
                return SendError("充值失败");
            }
            return SendSuccess("success", $result);
        } catch (\Exception $exception) {
            return SendError($exception->getMessage());
        }
    }

    /**
     *余额变动列表
     */
    public function topUpList()
    {
        $is_top_up = $this->request->param('is_top_up');
        $list = BalanceLog::where([
            'status' => 1,
            'is_top_up' => $is_top_up,
            'merchant_id' => $this->merchant_id
        ])->field('id,amount,create_time,edit,is_top_up')->order('id desc')->select()->toArray();
        return SendSuccess("success", $list);
    }
    /**
     * 获取余额充值凭证
     */
    public function getBalanceLog(){
        $balance_id = $this->request->param('balance_id');
        if(empty($balance_id)){
            return SendError('请传入账单id'[]);
        }
        $result = getbalance($balance_id);
        if($result==1){
            $result = getbalance($balance_id);
        }
        return SendSuccess('success', 'https://zdwy.kelimx.com/'.$result);
    }
    /**
     *水电账单列表
     */

    public function certificateList()
    {
        $type = $this->request->param('type');
        if (empty($type)) {
            return SendError("类型不存在");
        }
//        if (!in_array($type, [1, 2, 3, 4, 5,6,7,8])) {
//            return SendError("参数错误");
//        }
        $where = [];
        $where['merchant_id'] = $this->merchant_id;
        $where['pay_status'] = [1, -1];
        if ($type != 2) {
            $where['type'] = $type;
        }
        $list = Cost::where($where)
            ->with(['costType' => function ($e) {
                $e->field('id,cost_name as name,type')->find();
            }])
            ->field('id,merchant_id,all_amount,amount,pointId,real_amount,create_time,cost_type_id,remark,start_time,date_type,end_time,pay_status,number,electrity_type,pay_time,settlement_time,invoice')
            ->order('pay_time desc')
            ->where('all_amount','>',0)
            ->select();
        foreach ($list as $key => $value) {
            $list[$key]['start_time'] = date('Y/m/d', $value['start_time']);
            $list[$key]['end_time'] = date('Y/m/d', $value['end_time']);
            $list[$key]['checked'] = false;
        }
        return SendSuccess("success", $list);
    }

    /**
     * 转账审核列表
     */
    public function costAuditList()
    {
        $merchant_id = $this->merchant_id;
        $list = (new CostAudit())->with(['merchant'])->where(['merchant_id' => $merchant_id])->order('create_time desc')->select();
        if ($list->isEmpty()) {
            return SendSuccess('success', []);
        }
        $list = $list->toArray();
        foreach ($list as $k => $v) {
            $list[$k]['create_time'] = $v['up_time'];
        }
        return SendSuccess('success', $list);
    }

    /**
     *转账详情
     */
    public function costAuditDetail()
    {
        $id = $this->request->param("id/d",70);//父id
        if (empty($id)) {
            return SendError("请传入审核id");
        }
        $info = (new CostAudit())->find($id)->toArray();
        if (empty($info)) {
            return SendError('账单不存在');
        }
//        $info['create_time'] = date('Y-m-d', $info['create_time']);
        $info['create_time'] = $info['up_time'];
        $idArr = explode(',', $info['cost_id']);
        $list = [];
        foreach ($idArr as $k => $v) {
            $result = \app\common\model\tang\Cost::with(['merchants', 'costType'])->find($v)->toArray();
            if ($result) {
                $result['start_time'] = date('Y-m-d', $result['start_time']);
                $result['end_time'] = date('Y-m-d', $result['end_time']);
            }
            $list[] = $result;
        }
        $data['info'] = $info;
        $data['list'] = $list;
        return SendSuccess('success', $data);
    }

    /**
     *查看费率用电详情
     */
    public function certificateDetail()
    {
        $id = $this->request->param('id');
        $type = $this->request->param('electrity_type');
        if (empty($id)) {
            return SendError("类型不存在");
        }
        $where = [];
        $where['id'] = $id;
        $list = Cost::where($where)
            ->with(['costType' => function ($e) {
                $e->field('id,cost_name as name,type')->find();
            }, 'costRule' => function ($f) {
                $f->field('*,z_money as amount');
            }, 'merchants'])
            ->field('id,order_sn,subject_id,merchant_id,pay_time,all_amount as amount,pointId,real_amount,create_time,cost_type_id,remark,start_time,date_type,end_time,pay_status,number,create_time,settlement_time')
            ->find();
        if (empty($list)) {
            return SendError('订单不存在');
        }
        $invoice = (new Invoice())->where('costId', $id)->find();
        if (empty($invoice)) {
            $list['isInvoice'] = 0;
        } else {
            $list['isInvoice'] = $invoice['status'];
        }
        $list['time'] = date('Y.m.d H:i', $list['create_time']);
        $list['start_time'] = date('Y-m-d', $list['start_time']);
        $list['end_time'] = date('Y-m-d', $list['end_time']);
        if ($list['subject_id'] == 1) {
            $list['subject_id'] = '微信缴费';
        } else if ($list['subject_id'] == 2) {
            $list['subject_id'] = '余额缴费';
        } else {
            $list['subject_id'] = '转账/线下';
        }
        if ($type == 1) {//费率用电
            $newArray = rateElectricity($list);
            $list['inventory'] = $newArray;
        } else if ($type == 2) {//单一用电
            //查找用户对应表的记录
            $info = MonthSoleElectricityLog::alias('r')
                ->leftjoin('tang_watch_maintain w', 'r.pointId=w.pointId')
                ->leftjoin('tang_merchant t', 't.id=r.merchant_id')
                ->where([
                    'r.dataTime' => $list['settlement_time'],
                    'r.merchant_id' => $list['merchant_id'],
                ])
                ->field('t.id,t.merchant_sn,t.name,w.initial_degrees,r.merchant_id,r.userId,r.pointId,r.pointName,r.dataTime,
            r.rate,r.percent,r.totalMoney,r.totalPower,r.zongEnd,r.zongMoney,r.zongPower,r.zongStart,r.price,r.create_time')
                ->select()->toArray();
            foreach ($info as $key => $val) {
                $result = handWritten($val, $val['price']);
                $info[$key]['electricity'] = sprintf('%01.2f', $result['allElectricity']);
                $info[$key]['now_electricity'] = bcsub($val['zongEnd'], $val['zongStart'], 2);
                $info[$key]['money'] = sprintf('%01.2f', $result['allMoney']);
                $info[$key]['dataTime'] = date('Y-m', $val['create_time']);
            }
            $list['inventory'] = $info;
        } else if ($type == 3) {//单一用水
//            $info = (new MerchantModel())::alias('m')
            $info = (new MonthWaterLog())::alias('r')
                ->join('tang_watch_maintain w', 'r.pointId=w.pointId')
                ->leftjoin('tang_merchant t', 't.id=r.merchant_id')
                ->where([
                    'r.dataTime' => $list['settlement_time'],
                    'r.merchant_id' => $list['merchant_id'],
                    'r.pointId' => $list['pointId']
                ])
                ->field('t.id,t.merchant_sn,t.name,t.name,r.id as r_id,r.pointId,r.dataTime,w.pointName,r.start,r.end,r.rate,r.price')
                ->select()->toArray();
            foreach ($info as $key => $val) {
                $result = waterBill($val, $val['price']);
                $info[$key]['electricity'] = sprintf('%01.2f', $result['water']);
                $info[$key]['money'] = sprintf('%01.2f', $result['allMoney']);
            }
            $list['inventory'] = $info;
        }
        return SendSuccess("success", $list);
    }


    public function staffList()
    {
        $type = $this->request->param('type');
        if (empty($type)) {
            return SendError("类型不存在");
        }
        if (!in_array($type, [1, 2, 4, 5])) {
            return SendError("参数错误");
        }
        switch ($type) {
            case 1:
                $type = 9;
                break;
            case 2:
                $type = 10;
                break;
            case 4:
                $type = 112;
                break;
            case 5:
                $type = 113;
                break;
        }
        $where = [];
        $where['pay_status'] = [1, -1];
        $where['pid'] = 0;
        $where['type'] = 3;
        $where['merchant_id'] = $this->merchant_id;
        $where['cost_type_id'] = $type;
        $list = Cost::where($where)
            ->with(['costType' => function ($e) {
                $e->field('id,cost_name,type')->find();
            }])
            ->field('id,merchant_id,amount,real_amount,username,mobile,create_time,cost_type_id,remark,start_time,date_type,end_time,pay_status,number')
            ->select();
        foreach ($list as $key => $value) {
            $list[$key]['cost_type_id'] = $value['costType']['cost_name'];
//            $list[$key]['cost_type_id'] = $value['cost_type_id'] ==1 ? '员工证':'施工证';
            $list[$key]['time'] = date('Y.m.d H:i', $value['create_time']);
            if ($value['date_type'] == 1) {
                $list[$key]['date'] = '永久有效';
            } else {
                $list[$key]['date'] = date('Y/m/d', $value['start_time']) . '-' . date('Y/m/d', $value['end_time']);
            }
        }
        return SendSuccess("success", $list);
    }


    public function staffDetail()
    {
        $id = $this->request->param('id');
        if (empty($id)) {
            return SendError("ID不存在");
        }
        $where['id'] = $id;
        $where['merchant_id'] = $this->merchant_id;
        $list = Cost::where($where)
            ->with(['merchants', 'costType'])
            ->field('id,merchant_id,amount,real_amount,create_time,username,mobile,cost_type_id,remark,start_time,date_type,end_time,pay_status,number,id_card_positive,id_card_negative,other_certificate')
            ->find();
        if (empty($list)) {
            return SendError("证件不存在");
        }
        $list['time'] = date('Y.m.d H:i', $list['create_time']);
        $list['qrcode'] = 'http://qrcode.kelimx.com/qrcode/code?text=' . $list['id'];
//        $list['cost_type_id'] = $list['cost_type_id'] ==1 ? '员工证':'施工证';
        $list['cost_type_id'] = $list['costType']['cost_name'];
        $list['id_card_positive'] = $list['id_card_positive'] ? $this->request->domain() . $list['id_card_positive'] : '';
        $list['id_card_negative'] = $list['id_card_negative'] ? $this->request->domain() . $list['id_card_negative'] : '';
        $list['other_certificate'] = $list['other_certificate'] ? $this->request->domain() . $list['other_certificate'] : '';
        if ($list['date_type'] == 1) {
            $list['date'] = '永久有效';
        } else {
            $list['date'] = date('Y/m/d', $list['start_time']) . '-' . date('Y/m/d', $list['end_time']);
        }

        return SendSuccess("success", $list);
    }

    /**
     * 订单开票new
     */

    /**
     * 订单开发票
     */
    public function invoiceNew()
    {
        $param = $this->request->param('id/a');
        $invoiceType = $this->request->param('invoice_type');
        if (empty($param) || empty($invoiceType)) {
            return SendError('请传入账单或者开票类型');
        }
        $InvoiceModel = (new Invoice());
        if ($invoiceType == 2) {
            $cost = (new Cost())->with(['costType', 'merchant'])->whereIn('id', $param)->select();
            foreach ($cost as $k => $v) {
                if ($v['pay_status'] != 1) {
                    return SendError('该订单暂未支付,不能开票' . $v['id']);
                }
                if ($v['invoice'] > 0) {
                    return SendError('此账单已开过票或正在审核中' . $v['id']);
                }
            }
            $FPQQLSH = 'HFZD' . date('YmdHi') . rand(1000, 9999);
            $InvoiceInfo = (new MerchantInvoice())->where('merchant_id', $this->merchant_id)->find();
            $InvoiceModel->merchant_id = $this->merchant_id;
            $InvoiceModel->costId =trim(implode(',', $param),',') ;
            $InvoiceModel->orderNo = OrderSn();
            $InvoiceModel->invoiceSerialNum = $FPQQLSH;
            $InvoiceModel->title = $InvoiceInfo['title'];
            $InvoiceModel->bankAccount = $InvoiceInfo['bankAccount'];
            $InvoiceModel->bankName = $InvoiceInfo['bankName'];
            $InvoiceModel->companyAddress = $InvoiceInfo['companyAddress'];
            $InvoiceModel->taxNumber = $InvoiceInfo['taxNumber'];
            $InvoiceModel->email = $InvoiceInfo['email'];
            $InvoiceModel->type = $InvoiceInfo['type'];
            $InvoiceModel->createTime = time();
            $InvoiceModel->status = 0;
            $InvoiceModel->invoice_type = $invoiceType;
            $result = $InvoiceModel->save();
            //将订单开票状态更新成3待审核状态
            (new Cost())->whereIn('id', $param)->update(['invoice' => 3]);
            if ($result) {
                return SendSuccess('申请成功，等待审核');
            }
            return SendSuccess('申请开票失败');
        }
//        Db::startTrans();
        try {
            $comInfo = (new Config())->find(1);
            if ($comInfo['invoicesum'] <= 0) {
                return SendError('开票次数已用完,请联系商管人员');
            }
//            $ids = explode(',', $param['id']);
            $ids = $param;
            $allMoney = 0; //不含税总金额
            $allSE = 0;//总税额
            $allPayMoney = 0;//含税总额
            $FPQQLSH = 'HFZD' . date('YmdHi') . rand(1000, 9999);
            $cost = (new Cost())->with(['costType', 'merchant'])->whereIn('id', $ids)->select();
            if ($cost->isEmpty()) {
                return SendError('未找到账单');
            }
            $cost = $cost->toArray();
            $COMMON_FPKJ_XMXX = [];
            if (empty($cost[0]['merchant']['name']) || $cost[0]['merchant']['name'] == '-') {
                $merchant_brand = $cost[0]['merchant']['company'];
            } else {
                $merchant_brand = $cost[0]['merchant']['name'];
            }
            $BZ = '安徽省合肥市经济技术开发区金寨路与芙蓉路交口合肥正大广场 ' . $cost[0]['merchant']['positions_code'] . $merchant_brand;
            $time = '';
            foreach ($cost as $k => $v) {
                if ($v['pay_status'] != 1) {
                    return SendError('该订单暂未支付,不能开票');
                }
                if ($v['invoice'] > 0) {
                    return SendError('此账单已开过票或正在审核中' . $v['id']);
                }
                $allPayMoney += $v['all_amount'];
                if (empty($v['costType']['tax_code'])) {
                    return SendError('请联系商管维护' . $v['costType']['cost_name'] . '的税率编号');
                }
                $InvoiceInfo = (new MerchantInvoice())->where('merchant_id', $v['merchant_id'])->find();
                if (empty($InvoiceInfo)) {
                    return SendError('请先维护发票信息');
                }
//                $isFirst = $InvoiceModel->where('costId', $v['id'])->find();
//                if ($isFirst) {
//                    return SendError('请勿重复开票');
//                }
                $SPBM = str_pad($v['costType']['tax_code'], 19, "0", STR_PAD_RIGHT);
                $SL = $v['costType']['tax_rate'] / 100;
                if (empty($v['merchant']['name']) || $v['merchant']['name'] == '-') {
                    $merchant_brand = $v['merchant']['company'];
                } else {
                    $merchant_brand = $v['merchant']['name'];
                }
//                if(in_array($v['cost_type_id'],[1,2,3,9])){
                $time .= $v['costType']['cost_name'] . date('Y-m-d', $v['start_time']) . '~' . date('Y-m-d', $v['end_time']) . ';';
//                }
                if ($v['cost_type_id'] == 45 || $v['cost_type_id'] == 46) { //水电费发票走一个逻辑,牵扯服务费
                    if ($v['cost_type_id'] == 45) {
                        $fuwu = (new CostType())->find(50);
                        if (empty($v['fuwu_money']) && empty($v['add_price'])) { //查看是否有服务费//都为0,则没有电费服务费
                            $taxMoney = TaxMoney($v['all_amount'] / 100, 1, $v['costType']['tax_rate']);
                            $COMMON_FPKJ_XMXX[] =
                                [
                                    'FPHXZ' => 0,
                                    'SPBM' => $SPBM,
                                    'ZXBM' => '',
                                    'XMMC' => $v['costType']['goods_info'], //项目名称
                                    'XMJE' => $taxMoney['money'], //项目金额
                                    'SL' => $SL, //税率
                                    'SE' => $taxMoney['tax_money'], //税额
                                ];
                            $allMoney = $taxMoney['money'];
                            $allSE = $taxMoney['tax_money'];
                        } else {
                            $dianfei = TaxMoney($v['electric_money'] / 100, 1, 13);
                            $BLMoney = $dianfei['money'];
                            $dianBLMoney = $dianfei['tax_money'];
                            $fuwuMoney = TaxMoney($v['fuwu_money'] / 100, 1, 6);
                            $FWMoney = $fuwuMoney['money'];
                            $dianFWMoney = $fuwuMoney['tax_money'];
                            $allMoney = bcadd($BLMoney, $FWMoney, 2); //总不含税金额
                            $allSE = bcadd($dianBLMoney, $dianFWMoney, 2);//总税额
                            $COMMON_FPKJ_XMXX[] = [
                                'FPHXZ' => 0,
                                'SPBM' => $SPBM,
                                'ZXBM' => '',
                                'XMMC' => $v['costType']['goods_info'], //项目名称
                                'XMJE' => $BLMoney, //项目金额
                                'SL' => $SL, //税率
                                'SE' => $dianBLMoney, //税额
                            ];
                            $COMMON_FPKJ_XMXX[] = [
                                'FPHXZ' => 0,
                                'SPBM' => str_pad($fuwu['tax_code'], 19, "0", STR_PAD_RIGHT),
                                'ZXBM' => '',
                                'XMMC' => $fuwu['goods_info'], //项目名称
                                'XMJE' => $FWMoney, //项目金额
                                'SL' => $fuwu['tax_rate'] / 100, //税率
                                'SE' => $dianFWMoney, //税额
                            ];

                        }
                    } else {
                        $taxMoney = TaxMoney($v['all_amount'] / 100, 1, $v['costType']['tax_rate']);
                        $COMMON_FPKJ_XMXX[] =
                            [
                                'FPHXZ' => 0,
                                'SPBM' => $SPBM,
                                'ZXBM' => '',
                                'XMMC' => $v['costType']['goods_info'], //项目名称
                                'XMJE' => $taxMoney['money'], //项目金额
                                'SL' => $SL, //税率
                                'SE' => $taxMoney['tax_money'], //税额
                            ];
                        $allMoney += $taxMoney['money'];
                        $allSE += $taxMoney['tax_money'];
                    }
                } else {
                    $taxMoney = TaxMoney($v['all_amount'] / 100, 1, $v['costType']['tax_rate']);
                    $COMMON_FPKJ_XMXX[] =
                        [
                            'FPHXZ' => 0,
                            'SPBM' => $SPBM,
                            'ZXBM' => '',
                            'XMMC' => $v['costType']['goods_info'], //项目名称
                            'XMJE' => $taxMoney['money'], //项目金额
                            'SL' => $SL, //税率
                            'SE' => $taxMoney['tax_money'], //税额
                        ];
                    $allMoney += $taxMoney['money'];
                    $allSE += $taxMoney['tax_money'];
                }
            }
            $InvoiceModel->merchant_id = $cost[0]['merchant_id'];
            $InvoiceModel->costId = implode(',', $ids);;
            $InvoiceModel->orderNo = $cost[0]['order_sn'];
            $InvoiceModel->title = $InvoiceInfo['title'];
            $InvoiceModel->bankAccount = $InvoiceInfo['bankAccount'];
            $InvoiceModel->bankName = $InvoiceInfo['bankName'];
            $InvoiceModel->companyAddress = $InvoiceInfo['companyAddress'];
            $InvoiceModel->taxNumber = $InvoiceInfo['taxNumber'];
            $InvoiceModel->invoiceSerialNum = $FPQQLSH;
            $InvoiceModel->email = $InvoiceInfo['email'];
            $InvoiceModel->type = $InvoiceInfo['type'];
            $InvoiceModel->createTime = time();
            $InvoiceModel->save();
            if (empty($time)) {
                $BZ = '';
            } else {
                $BZ = $BZ . $time;
            }
            $contentData = [
                'REQUEST_COMMON_FPKJ' => [
                    "FPQQLSH" => $FPQQLSH,
                    "KPLX" => 0,
                    "BMB_BBH" => 0,
                    "ZSFS" => 0,
                    "XSF_NSRSBH" => $comInfo['tax'],//销售方纳税人识别号
                    "XSF_MC" => $comInfo['company'],//销售方名称
                    "XSF_DZDH" => $comInfo['adress'] . $comInfo['mobile'],//销售方地址、电话
                    "XSF_YHZH" => $comInfo['bank_account'],//销售方银行账号
                    "GMF_NSRSBH" => $InvoiceInfo['taxNumber'],//购买方纳税人识别号
                    "GMF_MC" => $InvoiceInfo['title'],//购买方名称
                    "GMF_DZDH" => $InvoiceInfo['companyAddress'],//购买方地址、电话
                    "GMF_YHZH" => $InvoiceInfo['bankAccount'],//购买方银行账号
                    "GMF_SJH" => $InvoiceInfo['telephone'],//购买方手机号
                    "GMF_DZYX" => $InvoiceInfo['email'],//购买方电子邮箱
                    "KPR" => $comInfo['people'],//开票人
                    "FHR" => $comInfo['FHR'],//复核人
                    "SKR" => $comInfo['SKR'],//收款人
                    "JSHJ" => $allPayMoney / 100,//价税合计
//                    "HJJE" => $allMoney,//合计金额,不含税
                    "HJJE" => bcsub($allPayMoney/100,$allSE,2),//合计金额,不含税
                    "HJSE" => $allSE,//合计税额
                    "BZ" => $BZ,
                    "COMMON_FPKJ_XMXXS" => [
                        'COMMON_FPKJ_XMXX' => $COMMON_FPKJ_XMXX
                    ]
                ]
            ];
            Log::info('-----开票信息开始-----');
            Log::info('info:'.json_encode($contentData));
            Log::info('-----开票信息结束-----');

            $GPservice = new GPService();
            $result = $GPservice->doJsonService($contentData);
//            Db::commit();
            return SendSuccess($result['returnMessage']);
        } catch (\Exception $exception) {
//            Db::rollback();
            return SendError($exception->getMessage());
        }
    }

    /**
     * 订单开发票
     */
    public function invoice()
    {
        $param = $this->request->param('id/a');
        $invoiceType = $this->request->param('invoice_type');
        if (empty($param) || empty($invoiceType)) {
            return SendError('请传入账单或者开票类型');
        }
        $InvoiceModel = (new Invoice());
        if ($invoiceType == 2) {
            $cost = (new Cost())->with(['costType', 'merchant'])->whereIn('id', $param)->select();
            foreach ($cost as $k => $v) {
                if ($v['pay_status'] != 1) {
                    return SendError('该订单暂未支付,不能开票' . $v['id']);
                }
                if ($v['invoice'] > 0) {
                    return SendError('此账单已开过票或正在审核中' . $v['id']);
                }
            }
            $FPQQLSH = 'HFZD' . date('YmdHi') . rand(1000, 9999);
            $InvoiceInfo = (new MerchantInvoice())->where('merchant_id', $this->merchant_id)->find();
            $InvoiceModel->merchant_id = $this->merchant_id;
            $InvoiceModel->costId =trim(implode(',', $param),',') ;
            $InvoiceModel->orderNo = OrderSn();
            $InvoiceModel->invoiceSerialNum = $FPQQLSH;
            $InvoiceModel->title = $InvoiceInfo['title'];
            $InvoiceModel->bankAccount = $InvoiceInfo['bankAccount'];
            $InvoiceModel->bankName = $InvoiceInfo['bankName'];
            $InvoiceModel->companyAddress = $InvoiceInfo['companyAddress'];
            $InvoiceModel->taxNumber = $InvoiceInfo['taxNumber'];
            $InvoiceModel->email = $InvoiceInfo['email'];
            $InvoiceModel->type = $InvoiceInfo['type'];
            $InvoiceModel->createTime = time();
            $InvoiceModel->status = 0;
            $InvoiceModel->invoice_type = $invoiceType;
            $result = $InvoiceModel->save();
            //将订单开票状态更新成3待审核状态
            (new Cost())->whereIn('id', $param)->update(['invoice' => 3]);
            if ($result) {
                return SendSuccess('申请成功，等待审核');
            }
            return SendSuccess('申请开票失败');
        }
//        Db::startTrans();
        try {
            $comInfo = (new Config())->find(1);
            if ($comInfo['invoicesum'] <= 0) {
                return SendError('开票次数已用完,请联系商管人员');
            }
//            $ids = explode(',', $param['id']);
            $ids = $param;
            $allMoney = 0; //不含税总金额
            $allSE = 0;//总税额
            $allPayMoney = 0;//含税总额
            $FPQQLSH = 'HFZD' . date('YmdHi') . rand(1000, 9999);
            $cost = (new Cost())->with(['costType', 'merchant'])->whereIn('id', $ids)->select();
            if ($cost->isEmpty()) {
                return SendError('未找到账单');
            }
            $cost = $cost->toArray();
            $COMMON_FPKJ_XMXX = [];
            if (empty($cost[0]['merchant']['name']) || $cost[0]['merchant']['name'] == '-') {
                $merchant_brand = $cost[0]['merchant']['company'];
            } else {
                $merchant_brand = $cost[0]['merchant']['name'];
            }
            $BZ = '安徽省合肥市经济技术开发区金寨路与芙蓉路交口合肥正大广场 ' . $cost[0]['merchant']['positions_code'] . $merchant_brand;
            $time = '';
            foreach ($cost as $k => $v) {
                if ($v['pay_status'] != 1) {
                    return SendError('该订单暂未支付,不能开票');
                }
                if ($v['invoice'] > 0) {
                    return SendError('此账单已开过票或正在审核中' . $v['id']);
                }
                $allPayMoney += $v['all_amount'];
                if (empty($v['costType']['tax_code'])) {
                    return SendError('请联系商管维护' . $v['costType']['cost_name'] . '的税率编号');
                }
                $InvoiceInfo = (new MerchantInvoice())->where('merchant_id', $v['merchant_id'])->find();
                if (empty($InvoiceInfo)) {
                    return SendError('请先维护发票信息');
                }
//                $isFirst = $InvoiceModel->where('costId', $v['id'])->find();
//                if ($isFirst) {
//                    return SendError('请勿重复开票');
//                }
                $SPBM = str_pad($v['costType']['tax_code'], 19, "0", STR_PAD_RIGHT);
                $SL = $v['costType']['tax_rate'] / 100;
                if (empty($v['merchant']['name']) || $v['merchant']['name'] == '-') {
                    $merchant_brand = $v['merchant']['company'];
                } else {
                    $merchant_brand = $v['merchant']['name'];
                }
//                if(in_array($v['cost_type_id'],[1,2,3,9])){
                $time .= $v['costType']['cost_name'] . date('Y-m-d', $v['start_time']) . '~' . date('Y-m-d', $v['end_time']) . ';';
//                }
                if ($v['cost_type_id'] == 45 || $v['cost_type_id'] == 46) { //水电费发票走一个逻辑,牵扯服务费
                    if ($v['cost_type_id'] == 45) {
                        $fuwu = (new CostType())->find(50);
                        if (empty($v['fuwu_money']) && empty($v['add_price'])) { //查看是否有服务费//都为0,则没有电费服务费
                            $taxMoney = TaxMoney($v['all_amount'] / 100, 1, $v['costType']['tax_rate']);
                            $COMMON_FPKJ_XMXX[] =
                                [
                                    'FPHXZ' => 0,
                                    'SPBM' => $SPBM,
                                    'ZXBM' => '',
                                    'XMMC' => $v['costType']['goods_info'], //项目名称
                                    'XMJE' => $taxMoney['money'], //项目金额
                                    'SL' => $SL, //税率
                                    'SE' => $taxMoney['tax_money'], //税额
                                ];
                            $allMoney+= $taxMoney['money'];
                            $allSE+= $taxMoney['tax_money'];
                        } else {
                            $dianfei = TaxMoney($v['electric_money'] / 100, 1, 13);
                            $BLMoney = $dianfei['money'];
                            $dianBLMoney = $dianfei['tax_money'];
                            $fuwuMoney = TaxMoney($v['fuwu_money'] / 100, 1, 6);
                            $FWMoney = $fuwuMoney['money'];
                            $dianFWMoney = $fuwuMoney['tax_money'];
                            $allMoney+= bcadd($BLMoney, $FWMoney, 2); //总不含税金额
                            $allSE+= bcadd($dianBLMoney, $dianFWMoney, 2);//总税额
                            $COMMON_FPKJ_XMXX[] = [
                                'FPHXZ' => 0,
                                'SPBM' => $SPBM,
                                'ZXBM' => '',
                                'XMMC' => $v['costType']['goods_info'], //项目名称
                                'XMJE' => $BLMoney, //项目金额
                                'SL' => $SL, //税率
                                'SE' => $dianBLMoney, //税额
                            ];
                            $COMMON_FPKJ_XMXX[] = [
                                'FPHXZ' => 0,
                                'SPBM' => str_pad($fuwu['tax_code'], 19, "0", STR_PAD_RIGHT),
                                'ZXBM' => '',
                                'XMMC' => $fuwu['goods_info'], //项目名称
                                'XMJE' => $FWMoney, //项目金额
                                'SL' => $fuwu['tax_rate'] / 100, //税率
                                'SE' => $dianFWMoney, //税额
                            ];

                        }
                    } else {
                        $taxMoney = TaxMoney($v['all_amount'] / 100, 1, $v['costType']['tax_rate']);
                        $COMMON_FPKJ_XMXX[] =
                            [
                                'FPHXZ' => 0,
                                'SPBM' => $SPBM,
                                'ZXBM' => '',
                                'XMMC' => $v['costType']['goods_info'], //项目名称
                                'XMJE' => $taxMoney['money'], //项目金额
                                'SL' => $SL, //税率
                                'SE' => $taxMoney['tax_money'], //税额
                            ];
                        $allMoney += $taxMoney['money'];
                        $allSE += $taxMoney['tax_money'];
                    }
                } else {
                    $taxMoney = TaxMoney($v['all_amount'] / 100, 1, $v['costType']['tax_rate']);
                    $COMMON_FPKJ_XMXX[] =
                        [
                            'FPHXZ' => 0,
                            'SPBM' => $SPBM,
                            'ZXBM' => '',
                            'XMMC' => $v['costType']['goods_info'], //项目名称
                            'XMJE' => $taxMoney['money'], //项目金额
                            'SL' => $SL, //税率
                            'SE' => $taxMoney['tax_money'], //税额
                        ];
                    $allMoney += $taxMoney['money'];
                    $allSE += $taxMoney['tax_money'];
                }
            }
            $InvoiceModel->merchant_id = $cost[0]['merchant_id'];
            $InvoiceModel->costId = implode(',', $ids);;
            $InvoiceModel->orderNo = $cost[0]['order_sn'];
            $InvoiceModel->title = $InvoiceInfo['title'];
            $InvoiceModel->bankAccount = $InvoiceInfo['bankAccount'];
            $InvoiceModel->bankName = $InvoiceInfo['bankName'];
            $InvoiceModel->companyAddress = $InvoiceInfo['companyAddress'];
            $InvoiceModel->taxNumber = $InvoiceInfo['taxNumber'];
            $InvoiceModel->invoiceSerialNum = $FPQQLSH;
            $InvoiceModel->email = $InvoiceInfo['email'];
            $InvoiceModel->type = $InvoiceInfo['type'];
            $InvoiceModel->createTime = time();
            $InvoiceModel->save();
            if (empty($time)) {
                $BZ = '';
            } else {
                $BZ = $BZ . $time;
            }
            $contentData = [
                'REQUEST_COMMON_FPKJ' => [
                    "FPQQLSH" => $FPQQLSH,
                    "KPLX" => 0,
                    "BMB_BBH" => 0,
                    "ZSFS" => 0,
                    "XSF_NSRSBH" => $comInfo['tax'],//销售方纳税人识别号
                    "XSF_MC" => $comInfo['company'],//销售方名称
                    "XSF_DZDH" => $comInfo['adress'] . $comInfo['mobile'],//销售方地址、电话
                    "XSF_YHZH" => $comInfo['bank_account'],//销售方银行账号
                    "GMF_NSRSBH" => $InvoiceInfo['taxNumber'],//购买方纳税人识别号
                    "GMF_MC" => $InvoiceInfo['title'],//购买方名称
                    "GMF_DZDH" => $InvoiceInfo['companyAddress'],//购买方地址、电话
                    "GMF_YHZH" => $InvoiceInfo['bankAccount'],//购买方银行账号
                    "GMF_SJH" => $InvoiceInfo['telephone'],//购买方手机号
                    "GMF_DZYX" => $InvoiceInfo['email'],//购买方电子邮箱
                    "KPR" => $comInfo['people'],//开票人
                    "FHR" => $comInfo['FHR'],//复核人
                    "SKR" => $comInfo['SKR'],//收款人
                    "JSHJ" => $allPayMoney / 100,//价税合计
//                    "HJJE" => $allMoney,//合计金额,不含税
                    "HJJE" => bcsub($allPayMoney/100,$allSE,2),//合计金额,不含税
                    "HJSE" => $allSE,//合计税额
                    "BZ" => $BZ,
                    "COMMON_FPKJ_XMXXS" => [
                        'COMMON_FPKJ_XMXX' => $COMMON_FPKJ_XMXX
                    ]
                ]
            ];
            Log::info('-----开票信息开始-----');
            Log::info('info:'.json_encode($contentData));
            Log::info('-----开票信息结束-----');

            $GPservice = new GPService();
            $result = $GPservice->doJsonService($contentData);
//            Db::commit();
            return SendSuccess($result['returnMessage']);
        } catch (\Exception $exception) {
//            Db::rollback();
            return SendError($exception->getMessage());
        }
    }

    /**
     * 获取员工证的费用项
     */
    public function getCostItem()
    {
        $cost = (new CostType())->where('pid', function ($query) {
            $query->table('tang_cost_type')->where(['type' => 3, 'pid' => 0])->field('id');
        })->field('cost_name,cost_money')->select();
        if ($cost->isEmpty()) {
            return SendError('暂无配置相应费包');
        } else {
            return SendSuccess('', $cost->toArray());
        }
    }

    /**
     * 获取银行
     */
    public function getBankInfo()
    {
        $result = (new CompanyConfig())->find(1);
        return SendSuccess('success', json_decode($result['back_number'], true));
    }

    /**
     * 商家添加员工
     */
    public function addEmployees()
    {
        $merchant_id = $this->merchant_id;
        $employees = $this->request->param('employess/a');
        Db::startTrans();
        try {
            $Merchant = MerchantModel::where(['id' => $merchant_id])->field('id,merchant_sn,status,mobile,username,company,name')->find();
            if (empty($Merchant)) {
                throw new Exception('商户不存在啊');
            }
            $money = (new CostType())->where('pid', function ($query) {
                $query->table('tang_cost_type')->where(['type' => 3, 'pid' => 0])->field('id');
            })->sum('cost_money');
            //生成费用单
            $cost['type'] = 3;
            $cost['is_user'] = 1;
            $cost['merchant_id'] = $merchant_id;
            $cost['amount'] = $money * 100 * count($employees);
            $cost['real_amount'] = $money * 100 * count($employees);
            $cost['add_user'] = $Merchant['name'];
            $cost['number'] = count($employees);
            $cost['unit_price'] = $money;
            $cost['date_type'] = 2;
            $cost['create_time'] = time();
            $cost['cost_type_id'] = (new CostType())->where('type', 3)->value('id');
            $cost['department_id'] = 6;
            $cost_id = (new Cost)->insertGetId($cost);
            if (empty($cost_id)) {
                throw new Exception('插入订单失败了');
            }
            foreach ($employees as $key => $val) {
                $employees[$key]['create_time'] = time();
                $employees[$key]['merchant_id'] = $merchant_id;
                $employees[$key]['money'] = $money;
                $employees[$key]['cost_id'] = $cost_id;
            };
            (new MerchantEmployees)->saveAll($employees);
            Db::commit();
            return SendSuccess('添加成功', $cost_id);
        } catch (\Exception $exception) {
            // 回滚事务
            Db::rollback();
            return SendError($exception->getMessage());
        }

    }

    /**
     * 获取缴费单列表
     */
    public function getEmList()
    {
        $merchant_id = $this->merchant_id;
        $cost = Cost::order('id desc')->where(['merchant_id' => $merchant_id, 'type' => 3])->field('id as cost_id,pay_status,number,create_time,pay_time,real_amount,amount')->select();
        if (!$cost->isEmpty()) {
            $cost = $cost->toArray();
            foreach ($cost as $key => $val) {
                $cost[$key]['name'] = MerchantEmployees::where('cost_id', $val['cost_id'])->column('name');;
                $cost[$key]['create_time'] = date('y-m-d H:i', $val['create_time']);
                $cost[$key]['real_amount'] = $val['real_amount'] / 100;
            }
            return SendSuccess('success', $cost);
        } else {
            return SendSuccess('暂无', '');
        }
    }

    /**
     * 获取缴费详情
     */
    public function getEmDetail()
    {
        $cost_id = $this->request->param('cost_id');
        if (empty($cost_id)) {
            return SendError('请传入正确的参数');
        }
        $list = MerchantEmployees::where('cost_id', $cost_id)->select();
        $money = Cost::where('id', $cost_id)->field('real_name')->find()->toArray();
        if (!$list->isEmpty()) {
            $data['money'] = $money;
            $data['list'] = $list;
            return SendSuccess('success', $data);
        } else {
            return SendSuccess('暂无', '');
        }
    }

    /**
     * 修改密码
     */
    public function UpdatePassword()
    {
        $oldPwd = $this->request->param('oldPwd');
        $newPwd = $this->request->param('newPwd');
        $pwd = $this->request->param('pwd');
        if (empty($oldPwd) || empty($newPwd) || empty($pwd)) {
            return SendError('请传入参数');
        }
        $merchantInfo = (new MerchantModel())->where('mobile', $this->mobile)->field('id,mobile,password')->find();//商户
        $staff = (new MerchantEmployees())->where('mobile', $this->mobile)->field('id,mobile,password')->find();//员工
        $release = (new ReleaseUser())->where('mobile', $this->mobile)->field('id,mobile,password')->find();//管理端
        if (empty($merchantInfo) && empty($staff) && empty($release)) {
            return SendError('信息不存在');
        }
        if ($merchantInfo) {
            $password = $merchantInfo['password'];
        }
        if ($staff) {
            $password = $staff['password'];
        }
        if ($release) {
            $password = $release['password'];
        }
        if (md5($oldPwd) != $password) {
            return SendError('原密码输入错误');
        }
        if (md5($newPwd) != md5($pwd)) {
            return SendError('新密码输入不一致');
        }
        if ($merchantInfo) {
            (new MerchantModel())->update([
                'password' => md5($newPwd)
            ], [
                'id' => $merchantInfo['id']
            ]);
            return SendSuccess('success', '修改密码成功3');
        }
        if ($staff) {
            (new MerchantEmployees())->update([
                'password' => md5($newPwd)
            ], [
                'id' => $staff['id']
            ]);
            return SendSuccess('success', '修改密码成功2');
        }
        if ($release) {
            (new ReleaseUser())->update([
                'password' => md5($newPwd)
            ], [
                'id' => $release['id']
            ]);
            return SendSuccess('success', '修改密码成功1');
        }

    }

    /**
     * 申请三关一闭
     */
    public function applyTask()
    {
        $merchant_info = (new MerchantModel())->where('id', $this->merchant_id)->field('id,name,company')->find();
        if (empty($merchant_info)) {
            return SendError('商户信息不存在');
        }
        $where['merchant_id'] = $merchant_info['id'];
        $where['merchant_name'] = $merchant_info['name'];
        $where['type'] = 1;
        $close = (new Close())->where($where)->whereTime('create_time', 'today')->find();
//        if ($close) {
//            return SendError('每天只能申报一次');
//        }
        $result = (new Close())->save($where);
        if ($result) {
            return SendSuccess('success');
        } else {
            return SendError('申请失败');
        }
    }
    public function costReceiptNew()
    {
        $id = $this->request->param('id');
        if (empty($id)) {
            return SendError('请传入账单id');
        }
        $result = mergeImage($id);
        if($result==1){
            $result = mergeImage($id);
        }
        return SendSuccess('success', 'https://zdwy.kelimx.com/'.$result);
    }
    //收据展示
    public function costReceipt()
    {
        $id = $this->request->param('id');
        if (empty($id)) {
            return SendError('请传入id');
        }
        $mch_info = (new Config())->find(1);
        $model = new Cost();
        $info = $model->with(['costType', 'merchants'])->where('pay_status', 1)->find($id);
        if (empty($info)) {
            return SendError('费用单不存在');
        }
        if ($info['start_time']) {
            $info['start_time'] = date('Y-m-d', $info['start_time']);
        }
        if ($info['end_time']) {
            $info['end_time'] = date('Y-m-d', $info['end_time']);
        }
        $time = explode('-', $info['pay_time']);
        $date = explode(' ', $time[2]);
        $result['time'] = $time[0] . ' 年 ' . $time[1] . ' 月 ' . $date[0] . ' 日';
        $result['No'] = $info['bill_no'];
        $result['shoujufang'] = $info['merchants']['company'];
        $result['amount'] = $info->all_amount / 100;
        $result['zje'] = moneyToString($result['amount']);
        $result['liushui'] = $info['order_sn'];
        $result['cost_sn'] = $info['costType']['cost_sn'];
        $result['positions_code'] = $info['merchants']['positions_code'];
        $result['brand'] = $info['merchants']['name'];
        $result['tenant_name'] = $info['merchants']['tenant_name'];
        $result['code'] = $info['merchants']['code'];
        $result['pay_user'] = $info['merchants']['tenant_name'];
        $result['title'] = $info['costType']['cost_name'] . '(' . $info['start_time'] . '~' . $info['end_time'] . ')';
        $result['image'] = 'https://zdwy.kelimx.com' . $mch_info['image'];
        $result['company'] = $mch_info['receipt_company'];
        if ($info['subject_id'] == 3) {
            $result['pay_way'] = '转账';
        } elseif ($info['subject_id'] == 2) {
            $result['pay_way'] = '余额';
        } else {
            $result['pay_way'] = '微信';
        }
        $result['remark'] = $mch_info['receipt_title'];
        return SendSuccess('success', $result);
    }

    /**
     * 更新订单信息
     */
    public function updateCost()
    {
        return SendSuccess('success', '更新成功');
    }

}